<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="知识标题" prop="title">
        <el-input
          v-input-restrict
          v-model="queryParams.title"
          placeholder="请输入知识标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="知识类目" prop="categoryId">
        <el-select
          v-model="queryParams.categoryId"
          placeholder="知识类目"
          filterable
          style="width: 200px"
        >
          <el-option label="全部" :value="undefined" />
          <el-option
            v-for="dict in categorylist"
            :key="dict.categoryId"
            :label="dict.categoryName"
            :value="dict.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="创建人"
        prop="createName"
        v-if="
          !(
            $store.getters.roles.length == 2 &&
            $store.getters.roles[0] == 'user'
          )
        "
      >
        <el-input
          v-input-restrict
          v-model="queryParams.createName"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <div class="commonMenu rela">
      <div
        class="abso radio"
        v-if="isManager($store.getters.roles) || isProfessional"
      >
        <el-radio-group
          @change="getList()"
          v-model="queryParams.dataScope"
          size="mini"
        >
          <el-radio-button label="0">全部</el-radio-button>
          <el-radio-button label="1">我的</el-radio-button>
        </el-radio-group>
      </div>
      <el-menu
        default-active=""
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <!-- 0待提交1待审核2已驳回3已通过，null就是全部 -->
        <el-menu-item index="">全部</el-menu-item>
        <el-menu-item index="0">待提交</el-menu-item>
        <el-menu-item index="2">品控/培训专员待审核</el-menu-item>
        <el-menu-item index="1">专业人员待审核</el-menu-item>
        <el-menu-item index="3">品控经理待审核</el-menu-item>
        <el-menu-item index="4">副总经理待审核</el-menu-item>
        <el-menu-item index="-1">已驳回</el-menu-item>
        <el-menu-item index="5">已审核</el-menu-item>
      </el-menu>
    </div>

    <el-table v-loading="loading" :data="postList">
      <el-table-column
        show-overflow-tooltip
        label="知识标题"
        align="center"
        prop="title"
      />
      <el-table-column
        width="120"
        label="封面"
        align="center"
        prop="knowledgePic"
      >
        <template slot-scope="scope">
          <el-image
            :src="
              scope.row.knowledgePic
                ? scope.row.knowledgePic
                : 'https://oss.metaxun.com/wx/zy/nocourse.png'
            "
            fit="cover"
            :width="120"
          />
        </template>
      </el-table-column>
      <el-table-column label="知识类目" align="center" prop="categoryName" />
      <el-table-column
        label="创建人"
        v-if="queryParams.dataScope == '0'"
        align="center"
        prop="createName"
      />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="postNames"
        v-if="queryParams.approval == '' || !queryParams.approval"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approval == 0">待提交</el-tag>
          <el-tag v-if="scope.row.approval == 5" type="success">已审核</el-tag>
          <el-tag v-if="scope.row.approval == 1" type="warning"
            >专业人员待审核</el-tag
          >
          <el-tag v-if="scope.row.approval == 2" type="warning"
            >品控/培训专员待审核</el-tag
          >
          <el-tag v-if="scope.row.approval == 4" type="warning"
            >待副总经理待审核</el-tag
          >
          <el-tag v-if="scope.row.approval == 3" type="warning"
            >待品控经理待审核</el-tag
          >
          <el-tag v-if="scope.row.approval == -1" type="danger">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240"
      >
        <template slot-scope="scope">
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
            >小程序预览</el-button
          >
          <el-button
            v-if="
              scope.row.createId == $store.getters.userId &&
              (scope.row.approval == -1 ||
                scope.row.approval == 5 ||
                scope.row.approval == 0)
            "
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <!-- 复制 草稿都可以复制 必须是自己的课程才能复制-->

          <el-button
            v-if="scope.row.createId == $store.getters.userId"
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleCopy(scope.row)"
            >复制</el-button
          >
          <!-- 提交审核/同步到正式课-->

          <el-button
            v-if="returnSubmit(scope.row, 'show') && scope.row.approval == 0"
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="
              handleSubmitAudit(scope.row, returnSubmit(scope.row, 'lable'))
            "
          >
            {{ returnSubmit(scope.row, "lable") }}
          </el-button>
          <!-- 审核 -->
          <el-button
            v-if="returnAudit(scope.row, 'show')"
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleAudit(scope.row)"
          >
            审核
          </el-button>
          <!-- 撤销审核 -->
          <el-button
            v-if="
              scope.row.createId == $store.getters.userId &&
              scope.row.approval > 0 &&
              scope.row.approval < 5
            "
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleCancelAudit(scope.row)"
          >
            撤销审核
          </el-button>

          <el-button
            v-if="
              scope.row.createId == $store.getters.userId &&
              scope.row.approval == -1
            "
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleReason(scope.row)"
          >
            驳回原因
          </el-button>

          <el-button
            v-if="
              scope.row.createId == $store.getters.userId &&
              (scope.row.approval == -1 ||
                scope.row.approval == 5 ||
                scope.row.approval == 0)
            "
            icon="el-icon-delete"
            size="mini"
            type="text"
            style="color: #e95756"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <rejectDia
      :type="rejectType"
      :open.sync="rejectOpen"
      :propform="rejectform"
      @refresh="rejectDiaReturn"
    ></rejectDia>
    <!-- 添加知识点 -->
    <addKnowledge
      :open.sync="addKnowledge_open"
      :type="addKnowledge_type"
      :id="addKnowledge_id"
      :categoryid="null"
      @refresh="getList()"
      @audit="executeAudit"
    ></addKnowledge>
    <!-- 品控经理 审核选择是否需要总经理 -->
    <div class="courseBaseDialog">
      <el-dialog :visible.sync="auditLevel3_open" width="420px">
        <div class="el-message-box__header" slot="title">
          <div class="el-message-box__title">
            <span>通过确认</span>
          </div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__container">
            <div class="el-message-box__status el-icon-warning"></div>
            <div class="el-message-box__message">点击确认，通过审核。</div>
          </div>
          <div style="margin: 15px 0 0 6px">
            <el-checkbox v-model="needStep4">是否需要副总经理复审</el-checkbox>
          </div>
        </div>

        <div class="el-message-box__btns">
          <el-button size="small" @click="auditLevel3_open = false"
            >取消</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="auditLevel3_handleAudit"
            >确定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 小程序预览 -->
    <konwledgeMiniDrawer
      :show.sync="konwledgeMiniDrawer_open"
      :prop_id="konwledgeMiniDrawer_id"
      :prop_step="konwledgeMiniDrawer_step"
    ></konwledgeMiniDrawer>
  </div>
</template>
  
<script>
import { isManager } from "@/utils/auth";
import { getCategoryList } from "@/api/knowledge/category";
import {
  getknowledgeTemporaryList,
  copyknowledge,
  putknowledgetemporary,
  submitknowledgetemporary,
  deleteknowledgetemporary,
  synchronizeknowledgetemporary,
  approvalknowledgetemporary,
  beforeCheck,
} from "@/api/knowledge/knowledge";
import { listPost_reviewConfig } from "@/api/configuration/auditConfiguration";
import rejectDia from "./components/rejectDia.vue";
import addKnowledge from "./components/addKnowledge";
import konwledgeMiniDrawer from "@/components/konwledgeMiniDrawer";
export default {
  name: "Course",
  dicts: ["sys_normal_disable"],
  components: { rejectDia, addKnowledge, konwledgeMiniDrawer },
  data() {
    return {
      konwledgeMiniDrawer_open: false,
      konwledgeMiniDrawer_step: 2,
      konwledgeMiniDrawer_id: "",

      auditLevel3_open: false,
      auditLevel3_row: {},

      addKnowledge_open: false,
      addKnowledge_type: 1,
      addKnowledge_id: null,

      isProfessional: false,
      categorylist: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined,
        createName: undefined,
        stauts: "",
        dataScope: "0",
      },
      rejectType: 1,
      rejectOpen: false,
      rejectform: {},
      // 获取配置
      needStep1: true,
      needStep2: true,
      needStep3: true,
      needStep4: false,
    };
  },
  activated() {
    this.getList();
  },
  async created() {
    // 检测是否时专业人员
    await this.isProfessionalId();
    // 获取列表的时候需要 上述是否是专业人员 来显示全部课程/我的
    this.getList();
    // 获取分类列表
    this.getCategorylist();
    // 获取配置
    this.getAuditConfig();
  },
  methods: {
    /* 是否是总部人员*/
    isManager(e) {
      return isManager(e);
    },
    /* 初始化-------------------------*/
    /* 检测是否时专业人员 */
    async isProfessionalId() {
      try {
        let res = await getCategoryList({
          professionalId: this.$store.getters.userId,
        });
        if (res.code == 200) {
          this.isProfessional = res.rows.length > 0 ? true : false;
          console.log("检测是否时专业人员", this.isProfessional);
        }
      } finally {
      }
    },
    /* 获取分类列表 并如果有的话获取 第一个分类获取详细*/
    async getCategorylist() {
      try {
        let res = await getCategoryList();
        if (res.code == 200) {
          this.categorylist = res.rows;
        }
      } finally {
      }
    },
    /* 获取课程审核配置 */
    async getAuditConfig() {
      try {
        let res = await listPost_reviewConfig({ reviewItem: 1 });
        if (res.code == 200) {
          this.needStep1 =
            res.rows.filter((item) => item.level == 1)[0].status == 0
              ? true
              : false;
          this.needStep2 =
            res.rows.filter((item) => item.level == 2)[0].status == 0
              ? true
              : false;
          this.needStep3 =
            res.rows.filter((item) => item.level == 3)[0].status == 0
              ? true
              : false;
        }
      } finally {
      }
    },
    // 获取table列表
    getList() {
      this.loading = true;
      let queryParams = { ...this.queryParams };
      if (
        this.$store.getters.roles.length == 1 &&
        this.$store.getters.roles[0] == "user" &&
        !this.isProfessional
      ) {
        queryParams.dataScope = "1";
      }
      getknowledgeTemporaryList(queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.$nextTick(() => {
          const refs = this.$refs;
          console.log(this.$refs);
          for (let key in refs) {
            if (
              key.includes("drop") &&
              refs[key] &&
              refs[key].menuItemsArray.every((item) => item.innerText == "")
            )
              refs[key].$el.style.display = "none";
          }
        });
        this.$forceUpdate();
      });
    },
    // 状态选择 查询列表
    handleSelect(key, keyPath) {
      this.queryParams.approval = key;
      this.getList();
    },

    /* 操作---------------------------- */
    /* !!!提交字眼的判断  返回是 提交审核还是同步到正式课*/
    /* type 有lable用于显示 同步到正式课/审核，show用于显示按钮是否存在 */
    returnSubmit(row, type) {
      // 不论是谁 只有自己能提交审核（这里需要从高级到低级判断）
      if (row.createId == this.$store.getters.userId) {
        // 如果是总经理创建
        if (
          this.$store.getters.roles.includes("gm") ||
          this.$store.getters.roles.includes("dgm")
        ) {
          return type == "lable" ? "同步至平台" : true;
        }
        // 如果是品控经理创建的
        else if (this.$store.getters.roles.includes("qcm")) {
          return type == "lable" ? "提交审核" : true;
        }
        // 如果是品控专员/培训专员创建
        else if (
          this.$store.getters.roles.includes("qcs") ||
          this.$store.getters.roles.includes("ts")
        ) {
          // 如果后面的配置全部关闭
          if (!this.needStep2 && !this.needStep3) {
            return type == "lable" ? "同步至平台" : true;
          } else {
            return type == "lable" ? "提交审核" : true;
          }
        }
        // 如果是普通员工创建
        else {
          // 如果后面的配置全部关闭
          if (!this.needStep1 && !this.needStep2 && !this.needStep3) {
            return type == "lable" ? "同步至平台" : true;
          } else {
            return type == "lable" ? "提交审核" : true;
          }
        }
      }
      // 如果不是自己则无法提交审核
      else {
        return type == "lable" ? "" : false;
      }
    },
    /* 提交审核 */
    async handleSubmitAudit(row, lable) {
      const loading = this.$loading({
        lock: true,
        text: "正在处理…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        let res;
        res = await submitknowledgetemporary(row.id, 1);
        if (res.code == 200) {
          this.$modal.msgSuccess(`${lable}成功`);
          this.getList();
        }
      } finally {
        loading.close();
      }
    },
    /* !!!审核按钮 根据角色是否显示*/
    returnAudit(row) {
      // 如果在专业人员审核
      if (
        row.approval == 1 &&
        row.professionalId == this.$store.getters.userId
      ) {
        return true;
      }
      // 如果是培训专员/品控专员
      else if (
        row.approval == 2 &&
        (this.$store.getters.roles.includes("qcs") ||
          this.$store.getters.roles.includes("ts"))
      ) {
        return true;
      }
      // 如果是品控经理
      else if (row.approval == 3 && this.$store.getters.roles.includes("qcm")) {
        return true;
      }
      // 如果是总经理副总经理
      else if (
        row.approval == 4 &&
        (this.$store.getters.roles.includes("gm") ||
          this.$store.getters.roles.includes("dgm")) &&
        row.isDgmApproval == 1
      ) {
        return true;
      } else {
        return false;
      }
    },
    /* 特殊审核 */
    async auditLevel3_handleAudit() {
      const loading = this.$loading({
        lock: true,
        text: "正在处理…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        let before = await beforeCheck(this.auditLevel3_row.id);
        if (before.code == 200) {
          let res = await approvalknowledgetemporary(
            this.auditLevel3_row.id,
            1,
            {
              isDgmApproval: this.needStep4 ? 1 : 0,
              rejected: "",
            }
          );
          if (res.code == 200) {
            this.$modal.msgSuccess(`审核成功`);
            this.auditLevel3_open = false;
            this.getList();
          }
        }
      } finally {
        loading.close();
      }
    },
    /* 审核接口执行函数 */
    async executeAudit(e) {
      let { row, status } = e;
      // 如果是通过
      if (status == 1) {
        // 如果是品控经理审核 需要指派是否需要总经理 比较特殊
        if (this.$store.getters.roles.includes("qcm")) {
          this.auditLevel3_open = true;
          this.auditLevel3_row = row;
        } else {
          const loading = this.$loading({
            lock: true,
            text: "正在处理…",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.6)",
          });
          try {
            let before = await beforeCheck(row.id);
            if (before.code == 200) {
              let res = await approvalknowledgetemporary(row.id, 1, {
                rejected: "",
              });
              if (res.code == 200) {
                this.$modal.msgSuccess(`审核成功`);
                this.getList();
              }
            }
          } finally {
            loading.close();
          }
        }
      }
      // 如果是驳回
      else {
        this.rejectType = 1;
        this.rejectform = row;
        this.rejectOpen = true;
      }
    },
    /* 审核操作 */
    async handleAudit(row) {
      this.addKnowledge_id = row.id;
      this.addKnowledge_open = true;
      this.addKnowledge_type = 4;
    },
    /* 驳回审核操作 */
    async rejectDiaReturn(e) {
      console.log(e);
      try {
        let before = await beforeCheck(e.id);
        if (before.code == 200) {
          let res = await approvalknowledgetemporary(e.id, 0, {
            rejected: e.rejected,
          });
          if (res.code == 200) {
            this.$modal.msgSuccess(`驳回审核成功`);
            this.getList();
          }
        }
      } finally {
      }
    },
    /* 撤销审核操作 */
    handleCancelAudit(row) {
      this.$confirm(
        `确认撤销【${row.title}】的审核申请吗?撤销后如需审核，需要重新提交审核申请！`,
        "撤销审核确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const loading = this.$loading({
            lock: true,
            text: "正在处理…",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.6)",
          });
          try {
            let res = await submitknowledgetemporary(row.id, 0);
            if (res.code == 200) {
              this.$modal.msgSuccess(`撤销审核成功`);
              this.getList();
            }
          } finally {
            loading.close();
          }
        })
        .catch(() => {});
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addKnowledge_open = true;
      this.addKnowledge_type = 1;
    },
    /* 编辑课程 */
    handleEdit(item) {
      if (item.port == "pc") {
        if (item.approval == 5 || item.approval == -1) {
          this.$confirm(
            `确定编辑【${item.title}】吗?编辑后将返回待提交`,
            "编辑确认",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              let data = { ...item };
              data.approval = 0;
              await putknowledgetemporary(data);
              this.getList();
              this.addKnowledge_open = true;
              this.addKnowledge_type = 2;
              this.addKnowledge_id = item.id;
            })
            .catch(() => {});
        } else {
          this.addKnowledge_open = true;
          this.addKnowledge_type = 2;
          this.addKnowledge_id = item.id;
        }
      } else {
        //消息提示 请前往小程序端编辑
        this.$message({
          type: "warning",
          message: "暂不支持编辑,请前往小程序端编辑",
        });
      }
    },
    /* 驳回原因 */
    handleReason(row) {
      this.rejectform = row;
      this.rejectOpen = true;
      this.rejectType = 3;
    },
    /* 复制 只能复制草稿*/
    handleCopy(row) {
      this.$confirm(`确定复制吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.6)",
          });
          try {
            let res = await copyknowledge(row.id);
            if (res.code == 200) {
              this.$modal.msgSuccess("复制成功");
              this.getList();
            }
          } finally {
            loading.close();
          }
        })
        .catch(() => {});
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$confirm(`确定删除【${row.title}】吗?删除后不可恢复！`, "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteknowledgetemporary(ids);
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /* 数据详情按钮 */
    handleDetail(row) {
      this.addKnowledge_open = true;
      this.addKnowledge_type = 3;
      this.addKnowledge_id = row.id;
    },
    handlePreview(row) {
      this.konwledgeMiniDrawer_open = true;
      this.konwledgeMiniDrawer_id = row.id;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
.courseBaseDialog {
  ::v-deep .el-dialog .el-dialog__header {
    border-bottom: none;
    padding: 0 !important;
  }
  ::v-deep .el-message-box__btns .el-button {
    margin-left: 10px;
  }
  ::v-deep .el-message-box__btns {
    padding-bottom: 10px;
  }
  ::v-deep .el-dialog .el-dialog__body {
    padding: 0px !important;
  }
}
.radio {
  z-index: 10;
  bottom: 9px;
  right: 0;
}
::v-deep .el-menu-item:hover {
  border-bottom: 1px solid #e6e6e6 !important;
}

::v-deep .el-menu--horizontal > .el-menu-item.is-active:hover {
  border-bottom: 2px solid #11a983 !important;
}
</style>
  